package com.ophiux.wechat.servlet.code;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ophiux.wechat.utils.StringUtil;
import com.ophiux.wechat.utils.WeChatPayUtil;

/**
 * 授权回调地址
 * @author chenh
 *
 */
public class CodeRedirectServlet extends HttpServlet{

	private static Logger logger = LoggerFactory.getLogger(CodeRedirectServlet.class);

	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		logger.info("code微信授权回调-进入回调");
		String code = request.getParameter("code");
	//	response.getWriter().write(code);

		String client_back_url = request.getParameter("client_back_url");
		
		logger.info("微信授权回调传递过来的参数："+"code="+code);
		if(StringUtil.isEmpty(code)){
			response.getWriter().write("用户拒绝授权");
		}else{
			
			/**
			 * 拼装重定向url
			 */
			StringBuffer sb = new StringBuffer();
			if(!client_back_url.contains("?")) {
				sb.append(client_back_url).append("?").append("code=").append(code);
			}else {
				//已经拼了参数
				sb.append(client_back_url).append("&code=").append(code);
			}
			//重定向
			logger.info("授权成功：重定向至终端："+sb.toString());
			response.sendRedirect(sb.toString());
		}
		
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	
}
